<script setup lang="ts">
import { Panel, Position, useNode, useVueFlow, VueFlow } from '@vue-flow/core'
import type { Node } from '@vue-flow/core'

const nodes = ref<Node[]>([
  {
    id: '1',
    position: { x: 50, y: 50 },
    data: { label: 'Node 1', hello: 'hello' },
    targetPosition: Position.Left, // or Bottom, Left, Right,
    sourcePosition: Position.Bottom, // or Top, Left, Right,
  },
  {
    id: '2',
    position: { x: 150, y: 50 },
    data: { label: 'Node 2' },
  },
])

/**
 * 通过这种方式添加的时候：其他已经移动过或者操作过的节点，会回到重新开始的状态。eg：移动node2，add一个node的时候，node2又回到原来的原点状态了。
 * eg：删除node1和node2，然后添加，发现都恢复了。
 * 而通过useVueFlow的方式不会有这个问题。
 */
const addNode = () => {
  const id = Date.now().toString()

  nodes.value.push({
    id,
    position: { x: 150, y: 50 },
    data: { label: `Node ${id}` },
  })
}

const { addNodes, updateNode, findNode, updateNodeData,removeNodes, getNodes  } = useVueFlow()

const generateRandomNode = () => {
  return {
    id: Math.random().toString(),
    position: { x: Math.random() * 500, y: Math.random() * 500 },
    label: 'Random Node',
  }
}

const onAddNode = () => {
  // add a single node to the graph
  addNodes(generateRandomNode())
}

const onAddNodes = () => {
  // add multiple nodes to the graph
  addNodes(Array.from({ length: 2 }, generateRandomNode))
}
/**
 * 这种删除也是：其他操作过的节点，会回到初始状态。且通过addNodes添加的节点，也会消失！！！
 * @param id
 */
const removeNode = (id: number | string) => {
  nodes.value = nodes.value.filter((node) => node.id !== id)
}

const removeOneNode = () => {
  removeNodes('1')
}

const removeMultipleNodes = () => {
  removeNodes(['1', '2'])
}
/*********更新操作*********/

console.log('beforeUpdate 更新前的nodes:', nodes)
const onSomeEvent = (nodeId: string) => {
  const node = nodes.value.find((node) => node.id === nodeId)

  console.log('当前node：', node)
  if (node) {
    node.data = {
      ...nodes.value[0].data,
      label: 'new Node 1',
      hello: 'world',
    }

    // you can also mutate properties like `selectable` or `draggable`
    node.selectable = false
    node.draggable = false
  }

  getNodesListLog()
}
const instance = useVueFlow()

const getNodesListLog = ()=>{
  console.log('updated 更新后的nodes-1:', nodes.value)
  nextTick(() => {
    console.log('updated 更新后的nodes-2:', nodes.value)
  })
  setTimeout(()=>{
    console.log('updated 更新后的nodes-3:', nodes.value)
  },1000)

  console.log('updated 更新后的nodes-4:', getNodes)
}
const updateNode1 = (nodeId: string) => {
  // use the `updateNodeData` method to update the data of an node
  // instance.updateNodeData(nodeId, { label: 'updateNodeData', hello: 'mona' })
  updateNodeData(nodeId, { label: 'updateNodeData', hello: 'mona' })

  getNodesListLog()
}
const updateNode2 = (nodeId: string) => {
  // find the node in the state by its id
  // const node = instance.findNode(nodeId)
  const node = findNode(nodeId)

  if (node) {
    node.data = {
      ...node.data,
      label: 'findNode',
      hello: 'world',
    }

    // you can also mutate properties like `selectable` or `draggable`
    node.selectable = false
    node.draggable = false
  }
  getNodesListLog()
}
const updateNode3 = (nodeId: string) => {
  // instance.updateNode(nodeId, {
  updateNode(nodeId, {
    data: {
      label: 'updateNode',
    },
    style: {
      // backgroundColor: '#f11'
    },
    selectable: false,
    draggable: false,
  })
  getNodesListLog()
}
// `useNode` returns us the node object straight from the state
// since the node obj is reactive, we can mutate it to update our nodes' data
// const { node } = useNode()

const updateNodeUseNode = (nodeId: string) => {
  // node.data = {
  //   ...node.data,
  //   hello: 'world',
  // }
  //
  // // you can also mutate properties like `selectable` or `draggable`
  // node.selectable = false
  // node.draggable = false
}
</script>

<template>
  <div style="height: calc(100vh - 60px)">
    <VueFlow :nodes="nodes">
      <Panel>
        <a-space>
          <!--添加-->
          <a-button @click="addNode">添加（push）</a-button>
          <a-button @click="onAddNode">添加（addNodes）</a-button>
          <a-button @click="onAddNodes">添加多个（addNodes）</a-button>

          <!--删除-->
          <a-button @click="removeNode('1')">删除node1（filter）</a-button>
          <a-button @click="removeNode('2')">删除node2（filter）</a-button>

          <a-button @click="removeOneNode">删除node1（removeNodes）</a-button>
          <a-button @click="removeMultipleNodes">删除node1和node2（removeNodes）</a-button>
        </a-space>
      </Panel>
      <Panel style="margin-top: 60px">
        <a-space>
          <!--  更新 -->
          <a-button @click="onSomeEvent('1')">Update Node 1</a-button>
          <a-button @click="updateNode1('1')">Update Node 1(updateNodeData)</a-button>
          <a-button @click="updateNode2('1')">Update Node 1(findNode)</a-button>
          <a-button @click="updateNode3('1')">Update Node 1(updateNode)</a-button>
          <a-button @click="updateNodeUseNode('1')">Update Node 1</a-button>
        </a-space>
      </Panel>

      <template #zoom-pane>
        <div>Some element inside the zoom pane</div>
      </template>
    </VueFlow>
  </div>
</template>

<style scoped></style>
